package com.cjw.campus.core.interceptor;

import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTException;
import cn.hutool.jwt.JWTUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
public class LoginInterceptor  implements HandlerInterceptor {

    @Override
    public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) {
//      声明请求头中的参数为字符串的token
        String token = request.getHeader("Authorization");

//      抛出异常
        try {
//          判断token是否能解析成功
            if (JWTUtil.verify(token, "1234".getBytes())) {
//              获取token 赋值给jwt
                JWT jwt = JWTUtil.parseToken(token);
//              获取前台用户信息
                Object object = jwt.getPayload("foregroundUser");
                System.out.println(JSONUtil.toJsonStr(object));
                System.out.println(jwt.getPayload("currentTime").toString());
//                获取生成token的时间戳
                Long tokenTime = Long.parseLong(jwt.getPayload("currentTime").toString());
//                获取当前时间戳
                Long currentTime = System.currentTimeMillis();
//                获取token存在时长的时间戳
                Long time = currentTime - tokenTime;
//                转化为分钟
                Long min = time / 1000L / 60L;
//                判断他是否小于30分钟
                if (min < 30L) {
//                    生效
                    return true;
                } else {
//                    失效
                    return false;
                }
            } else {
//                不能解析成功就失败
                return false;
            }
        } catch (JWTException e) {
            System.out.println(e);
            return false;
        }
//        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("postHandle执行{}", modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("afterCompletion执行异常{}", ex);
    }

}
